﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace WebManager.Function
{
    public partial class SetPortal : System.Web.UI.Page
    {
        private string oid = null;     
        private string ColumnID = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            oid = HttpContext.Current.Request.QueryString["oid"];
            ColumnID = HttpContext.Current.Request.QueryString["ColumnID"];
            if (ColumnID == null || oid == null)
            {
                Page.Response.Redirect("../errormsg.aspx");
            }
            if (!Page.IsPostBack)
            {
                LYQ.BLL.Doc bll = new LYQ.BLL.Doc();
                LYQ.Model.Doc model = bll.GetModel(oid);

                DocTitle.Text = model.Title;

                BindPortalFilter();
                BindProtalDescription();
            }
        }

        private void BindPortalFilter()
        {
            LYQ.BLL.PortalList bll = new LYQ.BLL.PortalList();          
            PortalFilter.DataTextField = "PortalName";
            PortalFilter.DataValueField = "PortalID";
            PortalFilter.DataSource = bll.GetModelList("");
            PortalFilter.DataBind();
        }
        private void BindProtalDescription()
        {
            LYQ.BLL.PortalList bllList = new LYQ.BLL.PortalList();
            LYQ.Model.PortalList modelList = bllList.GetModel(Convert.ToInt32(PortalFilter.SelectedValue));
            PortalDes.Text = "<br>本Portal文章数量最多为：" + modelList.Limit + "<br>" + modelList.Description+"<br>";

            int sum = 0;
            LYQ.BLL.Portal bll = new LYQ.BLL.Portal();
            DataSet ds = bll.GetList("PortalID = " + PortalFilter.SelectedValue);

            int t4 = ds.Tables[0].Select("PLevel=4").Length;//图片文章
            PortalDes.Text += "<br> 已有图片文章 : " + t4;
            sum += t4;

            int t3 = ds.Tables[0].Select("PLevel=3").Length;//标题加粗并且有简介
            PortalDes.Text += "<br> 已有标题加粗并且有简介文章 : " + t3;
            sum += t3;

            int t2 = ds.Tables[0].Select("PLevel=2").Length;//为标题加粗
            PortalDes.Text += "<br>已有为标题加粗文章 : " + t2;
            sum += t2;

            int t1 = ds.Tables[0].Select("PLevel=1").Length;//置顶文章
            PortalDes.Text += "<br> 已有置顶文章 : " + t1;
            sum += t1;

            int t0 = ds.Tables[0].Select("PLevel=0").Length;//一般级别
            PortalDes.Text += "<br> 已有一般文章 : " + t0;
            sum += t0;

            PortalDes.Text += "<br> 共计文章: " + sum;

        }

        protected void Save_Click(object sender, EventArgs e)
        {
            Label label = Page.Master.FindControl("lblTitle") as Label;
            LYQ.BLL.Portal bll = new LYQ.BLL.Portal();
            //得到栏目的ID和栏目名称
            LYQ.BLL.SysObj bllSysObj = new LYQ.BLL.SysObj();
            string ColumnName = bllSysObj.GetModel(ColumnID).OName;
          
            int portalID = Convert.ToInt32(PortalFilter.SelectedValue);
            LYQ.BLL.PortalList bllList = new LYQ.BLL.PortalList();
            LYQ.Model.PortalList modelList = bllList.GetModel(portalID);

            if (bll.Exists(portalID, oid))
            {
                label.Text = "该Portal已经存在该记录";
                return;
            }

            int sum = 0;   //总数
           
            DataSet ds = bll.GetList("PortalID = " + PortalFilter.SelectedValue);

            int t4 = ds.Tables[0].Select("PLevel=4").Length;//图片文章
            string t4ID = "";
            if(t4 > 0)
            {
                t4ID = ds.Tables[0].Select("PLevel=4")[0]["DocID"] as string;
            }
            sum += t4;

            int t3 = ds.Tables[0].Select("PLevel=3").Length;//标题加粗并且有简介
            string t3ID = "";
            if(t3 > 0)
            {
                t3ID = ds.Tables[0].Select("PLevel=3")[0]["DocID"] as string;
            }
            sum += t3;

          
            DataRow [] t2row = ds.Tables[0].Select("PLevel=2");
            int t2 = t2row.Length;//为标题加粗
            string t2ID = "";
            if (t2 > 0)
            {
                t2ID = t2row[0]["DocID"] as string;
            } 
            sum += t2;

            int t1 = ds.Tables[0].Select("PLevel=1").Length;//置顶文章          
            sum += t1;
            int t0 = ds.Tables[0].Select("PLevel=0").Length;//一般级别          
            sum += t0;

            LYQ.Model.Portal model = new LYQ.Model.Portal();      

            model.ColumnID = ColumnID;
            model.ColumnName = ColumnName;
            model.PortalID = portalID;
            model.PortalName = PortalFilter.SelectedItem.Text;
            model.DocID = oid;
            model.DocTitle = DocTitle.Text;
            model.CTime = DateTime.Now;
            model.PLevel = Convert.ToInt32(Type.SelectedValue);
            model.PortalName = PortalFilter.SelectedItem.Text;
            model.PLevelName = Type.SelectedItem.Text;


            string sql = "DECLARE  @DocID NVARCHAR(50)     SELECT TOP 1 @DocID =  DocID  FROM Portal WHERE PortalID = {0}  AND Plevel ={1} ORDER BY CTime ASC " +
                         "DELETE FROM Portal WHERE PortalID= {0} AND DocID = @DocID ";
            if (Type.SelectedValue == "4")
            {
                if (Session["PortalImageS"] == null)
                {
                    label.Text = "<b>请上传图片</b>";
                    return;
                }  
                if (t4 > 0)
                {
                    bll.Delete(portalID, t4ID);
                }

                model.ImagePath = Image2.ImageUrl;
               
            }
            else if (Type.SelectedValue == "3")
            {
                if (Summary.Text == "")
                {
                    label.Text = "<b>请输入Summary</b>";
                    return;
                }  
                else if(Summary.Text.Length < 80)
                {
                     label.Text = "<b>Summary字数太少，请增加</b>";
                    return;
                }
                else if(Summary.Text.Length > 120)
                {
                     label.Text = "<b>请输入Summary太多，经缩减</b>";
                    return;
                }
                if (t3 > 0)
                {
                    bll.Delete(portalID,t3ID);
                }
                model.Summary = Summary.Text;
            }
            else if (Type.SelectedValue == "2")
            {
                if (t2 > 0)
                {
                    bll.Delete(portalID, t2ID);
                }              
            }
            else if (Type.SelectedValue == "1")
            {
                int total = t4 + t3 + t2 + t1 + t0;
                if (total < modelList.Limit)
                {  //直接添加                   
                }
                else if(total >= modelList.Limit)
                {
                    //total = total - t0;
                    if (t0 > 0) //删除一篇最早的0级别文章
                    {
                        sql = string.Format(sql, portalID, 0);
                    }
                    else        //删除一篇最早的1级别文章
                    {
                        sql = string.Format(sql, portalID, 1);
                    }
                    Maticsoft.DBUtility.DbHelperSQL.ExecuteSql(sql);
                }
            }
            else
            {
                int total = t4 + t3 + t2 + t1 + t0;
                if (total >= modelList.Limit)
                {
                    sql = string.Format(sql, portalID, 0);
                    Maticsoft.DBUtility.DbHelperSQL.ExecuteSql(sql);
                }
            }

            bll.Add(model);
            GenerateHTML(portalID);
            string url = URLUtility.UrlBase + "/WebManager/Function/ListColumnContent.aspx?oid=" + ColumnID;
            Page.Response.Redirect(url);
        }

        private void  GenerateHTML(int  PortalID)
        {
            switch (PortalID)
            {
                case 2:
                    GenerateHTML2(PortalID);  break;                                  
                case 3:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                case 12:
                case 18:
                    GenerateHTML3TO12(PortalID);break;               
                case 14:                                     //十大疾病
                case 15:
                case 16:                 
                    GenerateHTMLType141516(PortalID);break;               
                case 17:                                    //特别关注
                    GenerateHTMLType17(PortalID); break;                
                case 13:                                    //首席专家                 
                case 4:                                     //健康常识
                    GenerateHTMLTypeNOColumn(PortalID); break;
                default:
                    GenerateHTMLTypeNOColumn(PortalID); break;
                   

            }
        }

        private void GenerateHTMLTypeNOColumn(int PortalID)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            LYQ.BLL.Portal bll = new LYQ.BLL.Portal();
            DataTable dt = bll.GetList("PortalID = " + PortalID + "  ORDER BY PLevel desc").Tables[0];
            DataRowCollection dr = dt.Rows;

            for (int i = 0; i < dr.Count; i++)
            {
                int TitleLength = 12;   //这个应该抽象出到PortalList       
                string docTitle = (dr[i]["DocTitle"] as string);          
                sb.Append("<li><a href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\" title=\"" + docTitle + "\"  target=\"_blank\">");
                if (docTitle.Length > TitleLength)
                    sb.Append(docTitle.Substring(0, TitleLength) + "</a></li>");
                else
                    sb.Append(docTitle + "</a></li>");
            }
            LYQ.BLL.PortalList portalListbll = new LYQ.BLL.PortalList();
            LYQ.Model.PortalList portallistmodel = portalListbll.GetModel(PortalID);
            portallistmodel.HTML = sb.ToString();
            portalListbll.Update(portallistmodel);
        }

        private void GenerateHTML2(int PortalID)
        {
            LYQ.BLL.Portal bll = new LYQ.BLL.Portal();
            DataTable dt = bll.GetList("PortalID =" + PortalID + " ORDER BY PLevel desc").Tables[0];

            DataRowCollection dr = dt.Rows;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<div class=\"hot_tit\"> <div class=\"hot_tit_left\"> <a target=\"_blank\" href=\"c.aspx?id=" + dr[0]["DocID"] as string + "\">");
            sb.Append("<img height=\"82\" widrh=\"84\" border=\"0\" src=\"" + (dr[0]["ImagePath"] as string).Replace("~", "") + "\" /></a></div><div class=\"hot_tit_right\">");
            sb.Append("<h3><a href=\"c.aspx?id=" + dr[1]["DocID"] as string + "\">" + dr[1]["DocTitle"] as string + "</a></h3><span class=\"title2\">核心提示:<a target=\"_blank\" href=\"c.aspx?id=" + dr[1]["DocID"] as string + "\">" + dr[1]["Summary"] as string + "</a></span></div></div>");


            sb.Append("<div class=\"hotnews_text\"><ul class=\"l\">");
            for (int i = 2; i < 7; i++)
                sb.Append("<li><a target=\"_blank\" href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\">" + dr[i]["DocTitle"] as string + "</a></li>");

            sb.Append("</ul><ul class=\"r\">");

            for (int i = 7; i < 12; i++)
                sb.Append("<li><a target=\"_blank\" href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\">" + dr[i]["DocTitle"] as string + "</a></li>");

            sb.Append("</ul></div>");
        

            LYQ.BLL.PortalList portalListbll = new LYQ.BLL.PortalList();
            LYQ.Model.PortalList portallistmodel = portalListbll.GetModel(PortalID);
            portallistmodel.HTML = sb.ToString();
            portalListbll.Update(portallistmodel);
        }

        private void GenerateHTML3TO12(int PortalID)
        {
            LYQ.BLL.Portal bll = new LYQ.BLL.Portal();
            DataTable dt = bll.GetList("PortalID =" + PortalID + " ORDER BY PLevel desc").Tables[0];
            DataRowCollection dr = dt.Rows;
            int MainTitleLen = 15;
            //int SubTitleLen = 10;
        

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<div class=\"sfocus\"><span class=\"pic\">");
            sb.Append("<a href=\"c.aspx?id=" + dr[0]["DocID"] as string + "\"><img alt=\"" + dr[0]["DocTitle"] as string + "\" src=\"" + (dr[0]["ImagePath"] as string).Replace("~", "") + "\"/></a></span>");

            string s = dr[0]["DocTitle"] as string;
            if (s.Length > 8)
            {
                sb.Append("<span class=\"txt\"><a href=\"c.aspx?id=" + dr[0]["DocID"] as string + "\">" + s.Substring(0, 8) + "</a></span></div>");
            }
            else
            {
                sb.Append("<span class=\"txt\"><a href=\"c.aspx?id=" + dr[0]["DocID"] as string + "\">" + s + "</a></span></div>");
            }


            sb.Append("<h4><b><a href=\"c.aspx?id=" + dr[1]["DocID"] as string + "\">");

            string t = dr[1]["DocTitle"] as string;
            if (t.Length > MainTitleLen)
            {
                sb.Append(t.Substring(0, MainTitleLen) + "</a></b></h4><ul>");
            }

            else
            {
                sb.Append(t + "</a></b></h4><ul>");
            }


            for (int i = 2; i < 5; i++)
            {
                int TitleLength = 12;
                int ColumnLength = 2;
               
                string colName = dr[i]["ColumnName"] as string;
                string docTitle = dr[i]["DocTitle"] as string;
              
                TitleLength = TitleLength + ColumnLength - colName.Length;

                if (docTitle.Length > TitleLength)
                {
                    sb.Append("<li><a href=\"col.aspx?p=" + dr[i]["ColumnID"] as string + "\">" + colName + "</a> | <a href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\">" + docTitle.Substring(0, TitleLength) + "</a></li>");
                }
                else
                {
                    sb.Append("<li><a href=\"col.aspx?p=" + dr[i]["ColumnID"] as string + "\">" + colName + "</a> | <a href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\">" + docTitle + "</a></li>");
                }
            }

            sb.Append("</ul><ul class=\"list2\">");

            for (int i = 5; i < 8; i++)
                sb.Append("<li><a href=\"col.aspx?p=" + dr[i]["ColumnID"] as string + "\">" + dr[i]["ColumnName"] as string + "</a> | <a href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\">" + dr[i]["DocTitle"] as string + "</a></li>");

            sb.Append("</ul>");          


            LYQ.BLL.PortalList portalListbll = new LYQ.BLL.PortalList();
            LYQ.Model.PortalList portallistmodel = portalListbll.GetModel(PortalID);
            portallistmodel.HTML = sb.ToString();
            portalListbll.Update(portallistmodel);
        }

        private void GenerateHTMLType17(int PortalID)
        {     
            LYQ.BLL.Portal bll = new LYQ.BLL.Portal();
            DataTable dt = bll.GetList("PortalID = " + PortalID + "  ORDER BY PLevel desc").Tables[0];
            DataRowCollection dr = dt.Rows;
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
           // sb.Append("<div class=\"pic\">");
            sb.Append("<a href=\"c.aspx?id=" + dr[0]["DocID"] as string + "\" target=\"_blank\"><img alt=\"" + dr[0]["DocTitle"] as string + "\" src=\"" + (dr[0]["ImagePath"] as string).Replace("~", "") + "\" width=\"175\" height=\"82\" border=\"0\"/></a>");
            sb.Append("<ul>");
            for (int i = 1; i < dr.Count; i++)
            {
                int TitleLength = 12;           
                string docTitle = (dr[i]["DocTitle"] as string);          
                sb.Append("<li><a href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\" title=\"" + docTitle + "\"  target=\"_blank\">");
                if (docTitle.Length > TitleLength)
                    sb.Append(docTitle.Substring(0, TitleLength) + "</a></li>");
                else
                    sb.Append(docTitle + "</a></li>");
            }
            sb.Append("</ul>");
            LYQ.BLL.PortalList portalListbll = new LYQ.BLL.PortalList();
            LYQ.Model.PortalList portallistmodel = portalListbll.GetModel(PortalID);
            portallistmodel.HTML = sb.ToString();
            portalListbll.Update(portallistmodel);
        }

        private void GenerateHTMLType141516(int PortalID)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            LYQ.BLL.Portal bll = new LYQ.BLL.Portal();
            DataTable dt = bll.GetList("PortalID = "+PortalID+"  ORDER BY PLevel desc").Tables[0];
            DataRowCollection dr = dt.Rows;          
            
            for (int i = 0; i < dr.Count; i++)
            {
                int TitleLength = 8;
                int ColumnLength = 2;
                string colTilte = (dr[i]["ColumnName"] as string);
                string docTitle = (dr[i]["DocTitle"] as string);

                if(colTilte.Length > 2)
                {
                    TitleLength = ColumnLength + TitleLength - colTilte.Length;
                } 

                sb.Append("<li><a href=\"col.aspx?p=" + colTilte +
                   "\" target=\"_blank\">" + (dr[i]["ColumnName"] as string) +
                   "</a> | <a href=\"c.aspx?id=" + dr[i]["DocID"] as string + "\" title=\""+docTitle+"\"  target=\"_blank\">");
               
                if (docTitle.Length > TitleLength)
                    sb.Append(docTitle.Substring(0, TitleLength) + "</a></li>");
                else
                    sb.Append(docTitle + "</a></li>");
            }

            LYQ.BLL.PortalList portalListbll = new LYQ.BLL.PortalList();
            LYQ.Model.PortalList portallistmodel = portalListbll.GetModel(PortalID);
            portallistmodel.HTML = sb.ToString();
            portalListbll.Update(portallistmodel); 
        }
        protected void Cancel_Click(object sender, EventArgs e)
        {
            string url = URLUtility.UrlBase + "/WebManager/Function/ListColumnContent.aspx?oid=" + ColumnID;
            Page.Response.Redirect(url);
        }

        protected void PortalFilter_SelectedIndexChanged(object sender, EventArgs e)
        {        
            BindProtalDescription();
        }

        protected void Type_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Type.SelectedIndex == 0)
            {
                UploadImageDiv.Visible = true;
                SummaryDiv.Visible = false;
            }
            else if (Type.SelectedIndex == 1)
            {
                UploadImageDiv.Visible = false;
                SummaryDiv.Visible = true;
            }
            else
            {  
                UploadImageDiv.Visible = false;
                SummaryDiv.Visible = false;
            }
        }

        protected void Upload2_Click(object sender, EventArgs e)
        {
            String savePath = @"~\uploads\portal\"+DateTime.Now.Year+@"\";
            string imagePath = savePath;
            savePath = Server.MapPath(savePath);
            if (FileUpload2.HasFile)
            {

                String fileName = DateTime.Now.ToString("yyyy-MM-dd") + FileUpload2.FileName;
                savePath += fileName;
                imagePath += fileName;
                FileUpload2.SaveAs(savePath);

                UploadStatusLabe2.Text = "您上传的文件被存储名字为： " + fileName;
                Session["PortalImageS"] = fileName;
                Image2.ImageUrl = imagePath;

            }
            else
            {
                // Notify the user that a file was not uploaded.
                UploadStatusLabe2.Text = "文件上传失败";
            }
        }
    }
}
